<?php
session_start(); if (!isset($_SESSION['uid'])) header('Location: login.php');
require_once 'config.php';
function db(): PDO {
    static $pdo; if (!$pdo) {
        $dsn = "mysql:host=$GLOBALS[DB_HOST];dbname=$GLOBALS[DB_NAME];charset=$GLOBALS[DB_CHAR]";
        $pdo = new PDO($dsn, $GLOBALS['DB_USER'], $GLOBALS['DB_PASS'], [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
    } return $pdo;
}
if ($_POST) {
    header('Content-Type: application/json');
    $act = $_POST['act'] ?? '';
    if ($act === 'save') {
        $id   = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name']);
        $code = trim($_POST['code']);
        $unit = trim($_POST['unit']);
        if ($name===''||$code==='') { echo json_encode(['res'=>0,'msg'=>'必填']); exit; }
        try {
            if ($id) db()->prepare('UPDATE goods SET name=?,code=?,unit=? WHERE id=?')->execute([$name,$code,$unit,$id]);
            else db()->prepare('INSERT INTO goods(name,code,unit) VALUES(?,?,?)')->execute([$name,$code,$unit]);
            echo json_encode(['res'=>1]); exit;
        } catch (PDOException $e) { echo json_encode(['res'=>0,'msg'=>'编码重复']); exit; }
    }
    if ($act === 'del' && isset($_POST['id'])) {
        db()->prepare('DELETE FROM goods WHERE id=?')->execute([$_POST['id']]);
        echo json_encode(['res'=>1]); exit;
    }
    if ($act === 'get' && isset($_POST['id'])) {
        echo json_encode(db()->prepare('SELECT * FROM goods WHERE id=?')->execute([$_POST['id']])->fetch(PDO::FETCH_ASSOC)); exit;
    }
}
$list = db()->query('SELECT * FROM goods ORDER BY id DESC')->fetchAll();
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>商品管理 - 仓库管理系统 V 0.1</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand fw-bold" href="index.php">仓库管理系统 V 0.1</a>
    <a class="btn btn-outline-light btn-sm" href="index.php">返回首页</a>
  </div>
</nav>
<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">商品列表</h5>
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#goodsModal" onclick="clearForm()">+ 新增</button>
  </div>
  <div class="table-responsive">
    <table class="table table-hover align-middle">
      <thead class="table-light"><tr><th>名称</th><th>编码</th><th>单位</th><th width="110">操作</th></tr></thead>
      <tbody id="tbody">
      <?php foreach ($list as $g): ?>
        <tr data-id="<?= $g['id'] ?>">
          <td><?= htmlspecialchars($g['name']) ?></td>
          <td><?= htmlspecialchars($g['code']) ?></td>
          <td><?= htmlspecialchars($g['unit']) ?></td>
          <td>
            <button class="btn btn-sm btn-warning" onclick="editGoods(<?= $g['id'] ?>)">编辑</button>
            <button class="btn btn-sm btn-danger" onclick="delGoods(<?= $g['id'] ?>)">删除</button>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="goodsModal" tabindex="-1">
  <div class="modal-dialog">
    <form id="goodsForm" class="modal-content">
      <input type="hidden" name="act" value="save">
      <input type="hidden" name="id" id="gid">
      <div class="modal-header">
        <h5 class="modal-title" id="modalTitle">新增商品</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3"><label>名称</label><input class="form-control" name="name" id="gname" required></div>
        <div class="mb-3"><label>编码</label><input class="form-control" name="code" id="gcode" required></div>
        <div class="mb-3"><label>单位</label><input class="form-control" name="unit" id="gunit" value="件"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary">保存</button>
      </div>
    </form>
  </div>
</div>

<script src="bootstrap.bundle.min.js"></script>
<script>
function clearForm(){gname.value=gcode.value=gunit.value='';gid.value='';modalTitle.innerText='新增商品';}
function editGoods(id){
  fetch('', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'act=get&id='+id})
  .then(r=>r.json()).then(d=>{
    gid.value=d.id;gname.value=d.name;gcode.value=d.code;gunit.value=d.unit;
    modalTitle.innerText='编辑商品'; new bootstrap.Modal('#goodsModal').show();
  });
}
function delGoods(id){
  if(!confirm('确定删除？'))return;
  fetch('', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'act=del&id='+id})
  .then(r=>r.json()).then(()=>location.reload());
}
document.getElementById('goodsForm').addEventListener('submit', e=>{
  e.preventDefault();
  fetch('', {method:'POST', body: new FormData(e.target)})
  .then(r=>r.json()).then(res=>{
    if(res.res){location.reload();}else{alert(res.msg);}
  });
});
</script>
</body>
</html>